declare 与类型声明文件
declare 为运行时已有的变量、函数、类或模块提供类型信息。它不创建实现,也不生成对应的 JavaScript 代码;声明正确并不代表运行时一定存在这个值。
声明变量、函数和类
declare const API_URL: string;
declare function greet(name: string): void;
declare class Person {
name: string;
constructor(name: string);
}
这些声明适合描述由脚本、宿主环境或构建工具提供的实体。若运行时没有提供 API_URL,读取它仍会报错。
对于全局库,应提供明确的接口,避免直接声明为 any:
interface JQuerySelection {
html(content: string): JQuerySelection;
}
declare const $: (selector: string) => JQuerySelection;
为第三方模块补充类型
没有类型声明的 JavaScript 模块,可以在 .d.ts 文件中描述其导出:
// my-library.d.ts:此文件不包含顶层 import/export
declare module 'my-library' {
export function doSomething(): void;
export const VERSION: string;
}
随后在业务代码中正常导入:
import { doSomething, VERSION } from 'my-library';
doSomething();
console.log(VERSION);
这里的声明只负责类型检查,库本身仍需安装并能在运行时加载。已有类型声明时,应优先使用库自带类型或对应的 @types 包。
扩展全局类型
带有顶层 import 或 export 的文件是模块,需要用 declare global 扩展全局类型:
// global.d.ts
export {};
declare global {
interface Window {
myAppConfig: {
apiUrl: string;
};
}
}
运行时代码负责实际赋值:
window.myAppConfig = { apiUrl: '/api' };
export {} 使声明文件成为模块,declare global 中的类型扩展仍作用于全局。没有顶层导入、导出的声明文件本身处于全局作用域,可以直接声明全局接口。
声明文件的生效条件
.d.ts 用于存放类型声明,例如 global.d.ts、env.d.ts 和 node_modules/@types 下的声明文件。
- 声明文件需要被
tsconfig.json的files、include或导入依赖覆盖。 - 顶层
declare const在全局声明文件中声明全局变量,在模块中则仅属于该模块。 - 模块文件中的
declare module '已有模块'用于模块扩展,与声明一个尚无类型的模块不同。 - 类型声明只影响编译器,实际实现和初始化仍由运行时代码负责。